import { defineStore } from 'pinia'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { login, getUserInfo, logout } from '../../api/sys'
import { setItem, getItem, removeAll } from '@/utils/storage'
import { TOKEN, CODE } from '@/contant'

// 用户相关
export const useUserStore = defineStore('user', {
  state: () => ({
    token: getItem(TOKEN) || '',
    userInfo: getItem('userInfo') || ''
  }),
  getters: {
    hasUserInfo: (state) => JSON.stringify(state.userInfo) !== '{}'
  },
  actions: {
    // 登录
    async login(userInfo) {
      const res = await login(userInfo)
      if (res?.code === CODE.SUCCESS) {
        this.token = res.token
        this.userInfo = res
        setItem(TOKEN, res.token)
        setItem('userInfo', res)
        ElMessage({ message: res.message, type: 'success' })
        router.push('/admin')
      } else {
        ElMessage({ message: res.message, type: 'error' })
      }
    },
    // 获取用户信息
    async getUserInfo() {
      const res = await getUserInfo()
      this.userInfo = res
      setItem('userInfo', res.data)
    },
    // 退出
    async logout() {
      const res = await logout()
      if (res.code === 0) {
        ElMessage({ message: res.message, type: 'success' })
        this.token = ''
        this.userInfo = ''
        removeAll()
        router.push({ path: '/login' })
      }
    }
  }
})
